package cn.mabach.modules.EsLog;

import cn.mabach.result.RS;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author: ming
 * @Date: 2020/2/14 0014 上午 12:09
 */
@RestController
@Slf4j
public class EsLogController {


    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;



    @GetMapping("/getWebLog")
    public Map getLog(@RequestParam(value = "keyword", required = false) String keyword,
                      @RequestParam(value = "time", required = false) Date time,
                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        //创建顶级的查询条件对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //创建组合查询条件对象(这里可以放多种查询条件)
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();


        if (!StringUtils.isEmpty(keyword)) {
            //operator(Operator.AND)是控制切分词后, 根据每个词查询出来结果, 这些结果组合在一块返回的关系
            boolQueryBuilder.must(QueryBuilders.matchQuery("message", keyword).operator(Operator.AND));
        }

//        时间查询
        if (!StringUtils.isEmpty(time)){
            log.info("time:{}",time);
            boolQueryBuilder.must(QueryBuilders.matchQuery("logdate",time).operator(Operator.AND));
        }


        //时间聚合查询, requestTime这个名称随意起名, 主要用来获取结果的时候, 通过这个名字获取结果


        //将组合查询对象放入顶级查询对象中
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        /**
         * 分页查询，第一个参数：当前页，从0开始计算
         * 第二个参数：每页显示多少条
         */
        nativeSearchQueryBuilder.withPageable(PageRequest.of(pageNum-1,pageSize));

        /**
         * 查询并返回结果集
         */
        AggregatedPage<InfologEntity> infologEntities = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), InfologEntity.class);
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<Map> arrayList = new ArrayList<>();
        List<InfologEntity> content = infologEntities.getContent();
        for (InfologEntity entity : content) {
            String message = entity.getMessage();
            Map parseObject = JSON.parseObject(message, Map.class);
            parseObject.put("request_time",entity.getLogdate());
            arrayList.add(parseObject);
        }

        map.put("list",arrayList);
        map.put("total",infologEntities.getTotalElements());
        log.info("结果:{}",map);

        return map;


    }
}









//
//    @GetMapping("/getErrorLog")
//    public Map getErrorLog(@RequestParam(value = "keyword", required = false) String keyword,
//                      @RequestParam(value = "time",required = false)String time,
//                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
//                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
//        if (StringUtils.isEmpty(keyword)&&StringUtils.isEmpty(time)){
//            requestArgs="{\"from\": %d,\"size\": %d ,\"query\": {\"match_all\": {}}}";
//        }
//        if (!StringUtils.isEmpty(keyword)){
//            keyword="";
//        }
//
//        if (StringUtils.isEmpty(time)){
//            time="";
//        }
//        String args=keyword+" "+time;
//        String format = String.format(errorUrl, pageSize*(pageNum-1), pageSize,args);
//
//        log.info("format:{}",format);
//
//
//        Map map = restTemplate.postForObject(infoUrl, format, Map.class);
//        Map hits = (Map) map.get("hits");
//
//
//        Integer total = (Integer) hits.get("total");
//        System.out.println("total:"+total);
//        List<Map> s = (List) hits.get("hits");
//        ArrayList<Map> list = new ArrayList<>();
//        for (Map map1 : s) {
//            Map source = (Map) map1.get("_source");
//            String message = (String) source.get("message");
//            Map parseObject = JSON.parseObject(message, Map.class);
//            list.add(parseObject);
//
//        }
//        HashMap<String, Object> result = new HashMap<>();
//        result.put("total",total);
//        result.put("list",list);
//
//        return result;
//    }

